const express = require("express")
const router = express.Router();
const bcrypt = require("bcryptjs");
const passport = require("passport")
const Core = require('@alicloud/pop-core');
// 引入takon
var jwt = require('jsonwebtoken');


// 引入users
const User = require("../../models/User");
//产生随机数
function getCode() {
    let str = "";
    for (let i = 0; i < 4; i++) {
        str += parseInt(Math.random() * 10);
    }
    return str;
};
let mes = Number;
router.post("/mes", (req, res) => {
        console.log("请求了");
        // res.status(200).json('ok')
        const mesgg = req.body.mes;
        // 产生随机数
        let str1 = getCode();
        mes = str1;
        // console.log(mesgg);
        var client = new Core({
            accessKeyId: 'LTAI4FohhX6dxQsJ2NuRRJqH',
            accessKeySecret: '3Kvdg1wmoonYVpww5x9R6wk7HyzlCd',
            endpoint: 'https://dysmsapi.aliyuncs.com',
            apiVersion: '2017-05-25'
        });
        var params = {
            "RegionId": "cn-hangzhou",
            "PhoneNumbers": mesgg,
            "SignName": "菜鸟客栈",
            "TemplateCode": "SMS_186576354",
            "TemplateParam": `{"code":'${str1}'}`
        }
        var requestOption = {
            method: 'POST'
        };
        client.request('SendSms', params, requestOption).then((result) => {
            // console.log(JSON.stringify(result));
            console.log(result);

            res.json(result)
        }, (ex) => {
            // console.log(ex);
        })
    })
    //返回token jwt api/users/Login
router.post("/register", (req, res) => {
    // console.log(req.body);
    // console.log(mes);
    if (req.body.mes !== mes) {
        res.status(400).json('手机验证码错误')

    } else {
        User.findOne({ phone: req.body.phone }).then((phone) => {
            if (phone && phone) {
                return res.status(400).json("手机已被注册")
            } else {
                const newUser = new User({
                    username: req.body.username,
                    password: req.body.password,
                    inentity: req.body.inentity,
                    phone: req.body.phone,
                })
                bcrypt.genSalt(10, function(err, salt) {
                    bcrypt.hash(newUser.password, salt, (err, hash) => {
                        if (err) {
                            res.status(400).json("手机注册失败")
                        }
                        newUser.password = hash;
                        newUser.save()
                            .then(user => res.json(user))
                            .catch(err => console.log(err))
                    })
                })
            }
        })
    }

})
router.post("/login", (req, res) => {
        const username = req.body.username;
        const password = req.body.password;
        // 查询数据库
        User.findOne({ username })
            .then(user => {
                if (!user) {
                    return res.status(404).json("用户不存在");
                }
                // 设置token
                bcrypt.compare(password, user.password).then(isMach => {
                    if (isMach) {
                        const rule = {
                            id: user.id,
                            username: user.username,
                            identity: user.identity
                        };
                        //    jwt.sign("规则","jiamimingz","过期时间","箭头函数")
                        jwt.sign(rule, "pop", { expiresIn: 3600 }, (err, token) => {
                            if (err) {
                                res.json("token未设置")
                            } else {
                                res.json({
                                    success: true,
                                    token: "Bearer " + token,
                                    id: user.id,
                                    name: user.name
                                })
                            }
                        })
                    } else {
                        return res.status(400).json("密码错误")
                    }
                })
            })
    })
    // User.find().then(res => console.log(res))
router.get("/", passport.authenticate("jwt", { session: false }), async(req, res) => {
    const data = await User.find()
    res.json(data)
        // console.log(data);
})
router.delete('/delete/:id', passport.authenticate("jwt", { session: false }), async(req, res) => {
        const data = await User.findOneAndDelete({ _id: req.params.id })
        res.json(data)
            // console.log(data);
    })
    // $router
    // @desc return current user
module.exports = router;